package com.lantosec.hmrp.modules.category.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lantosec.hmrp.core.kit.PageVO;
import com.lantosec.hmrp.core.shiro.TokenUtil;
import com.lantosec.hmrp.core.util.BeanUtils;
import com.lantosec.hmrp.core.util.Calculateutils;
import com.lantosec.hmrp.modules.category.entity.*;
import com.lantosec.hmrp.modules.category.mapper.AssetsCheckPlanMapper;
import com.lantosec.hmrp.modules.category.service.IAssetsCheckDetailedService;
import com.lantosec.hmrp.modules.category.service.IAssetsCheckNoteService;
import com.lantosec.hmrp.modules.category.service.IAssetsCheckPlanService;
import com.lantosec.hmrp.modules.category.service.IAssetsInfoService;
import com.lantosec.hmrp.modules.category.vo.AssetsCheckPlanVO;
import com.lantosec.hmrp.modules.category.vo.UserInfoVO;
import com.lantosec.hmrp.modules.system.entity.RegionalHead;
import com.lantosec.hmrp.modules.system.service.ISysAreaService;
import com.lantosec.hmrp.modules.system.service.ISysDeptService;
import com.lantosec.hmrp.modules.system.service.ISysUserService;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * <p>
 * 盘点计划 服务实现类
 * </p>
 *
 * @author AutoCode
 * @since 2020-04-01
 */
@Service
@Primary
@Log4j2
@SuppressWarnings("all")
public class AssetsCheckPlanServiceImpl extends ServiceImpl<AssetsCheckPlanMapper, AssetsCheckPlan> implements IAssetsCheckPlanService {

    @Autowired
    private IAssetsCheckDetailedService detailedService;

    @Autowired
    private IAssetsInfoService assetsInfoService;

    @Autowired
    private IAssetsCheckNoteService checkNoteService;

    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private ISysAreaService areaService;

    @Autowired
    private ISysUserService userService;

    @Override
    public Page<AssetsCheckPlan> queryPage(PageVO<AssetsCheckPlan> page, AssetsCheckPlanVO condition) {
        Integer pCount = 0;
        Integer aCount = 0;
        double schedule = 0;
        String userId = TokenUtil.getUserId();
        //获取所有的盘点计划
        PageVO<AssetsCheckPlan> result = baseMapper.selectPage(page, new QueryWrapper<AssetsCheckPlan>()
                .eq("flag", 0)
                .eq("review_user_id",userId)
                .orderByDesc("create_time"));
        for (AssetsCheckPlan it : result.getRecords()) {
            String planId = it.getPlanId();
            //盘点人数
            List<AssetsCheckDetailed> list = detailedService.list(new QueryWrapper<AssetsCheckDetailed>()
                    .eq("plan_id", planId)
                    .groupBy("plan_id", "check_user_id"));
            it.setPCount(list.size());
            //区域或部门固定资产总数
            aCount = getCount(aCount, it);
            it.setACount(aCount);
            //盘点计划已经盘点完成的总数
            int checkCount = checkNoteService.count(new QueryWrapper<AssetsCheckNote>()
                    .eq("plan_id", planId));
            //进度
            if(aCount == 0 || checkCount == 0){
                it.setSchedule(0.0);
            }else{
                it.setSchedule( Calculateutils.roundRatio(checkCount,aCount));
            }
            //审核进度
            Double aDouble = unCheckCount(planId, checkCount);
            it.setReviewProgress(aDouble);

            //审核人
            String reviewUserId = it.getReviewUserId();
            String name = userService.getById(reviewUserId).getName();
            it.setReviewUser(name);
        }
        return page.setRecords(result.getRecords());
    }

    private Double unCheckCount(String planId,Integer checkCount) {
        int check = checkNoteService.count(new QueryWrapper<AssetsCheckNote>()
                .in("review_state", 1,2)
                .eq("plan_id",planId));
        if(check == 0 || checkCount == 0){
           return 0.0;
        }else{
            double v = Calculateutils.roundRatio(check, checkCount);
            return v;
        }
    }

    private Integer getCount(Integer aCount, AssetsCheckPlan it) {
        String planId = it.getPlanId();
        Integer planType = it.getPlanType();  //1区域 2部门
        //查询盘点计划是否存在按物资类别盘点
        String categoryList = categoryList(planId);
        //获取盘点计划对应的计划明细信息
        List<AssetsCheckDetailed> list = detailedService.list(new QueryWrapper<AssetsCheckDetailed>()
                .eq("plan_id", planId));
        for (AssetsCheckDetailed its : list) {
            String areaId = its.getAreaId();
            String deptId = its.getDeptId();
             aCount += baseMapper.getCount(areaId,deptId,categoryList);
        }
        return aCount;

       /* if(1 == planType){
            //区域总资产数
            for (AssetsCheckDetailed its : list) {
                String areaId = its.getAreaId();
                for (String s : asList) {
                aCount += assetsInfoService.count(new QueryWrapper<AssetsInfo>()
                        .eq("area_id", areaId)
                        .eq(String.valueOf(AssetsInfo.ColName.review_state),1)
                        .eq(StringUtils.isNotEmpty(s),String.valueOf(AssetsInfo.ColName.category_id),s)
                        .groupBy("area_id"));
                }
            }
        }else{
            //部门总资产数
            for (AssetsCheckDetailed its : list) {
                String deptId = its.getDeptId();
                for (String s : asList) {
                aCount += assetsInfoService.count(new QueryWrapper<AssetsInfo>()
                        .eq("use_dept_id",deptId)
                        .eq(String.valueOf(AssetsInfo.ColName.review_state),1)
                        .eq(StringUtils.isNotEmpty(s),String.valueOf(AssetsInfo.ColName.category_id),s)
                        .groupBy("use_dept_id"));
                }
            }
        }*/
    }

    @Override
    public String categoryList(String planId) {
        return baseMapper.selectOne(new QueryWrapper<AssetsCheckPlan>()
                    .eq(String.valueOf(AssetsCheckPlan.ColName.plan_id), planId)).getCategoryList();
    }

    @Override
    public List<UserInfoVO> queryUserList() {
        List<UserInfo> userInfos = baseMapper.queryUserList();
        return BeanUtils.entity2VO(userInfos);
    }

    @Override
    public RegionalHead queryName(RegionalHead entity) {
        List list = new ArrayList();
        List idList = new ArrayList();
        if(StringUtils.isNotEmpty(entity.getAreaId())){
            String areaId = entity.getAreaId();
            List<String> areaIdList = Arrays.asList(areaId.split(","));
            areaIdList.forEach(it->{
                if("all".equals(it)){
                    entity.setFlag("所有区域");
                    return;
                }
                String areaName = areaService.getById(it).getAreaName();
                String name = userService.getById(entity.getUserId()).getName();
                list.add(areaName);
                idList.add(it);
                entity.setAreaName(StringUtils.join(list,","));
                entity.setAreaId(StringUtils.join(idList,","));
                entity.setUserName(name);
            });
        }else{
            String deptId = entity.getDeptId();
            List<String> deptIds = Arrays.asList(deptId.split(","));
            deptIds.forEach(it->{
                if("all".equals(it)){
                    entity.setFlag("所有部门");
                    return;
                }
                String deptName = deptService.getById(it).getDeptName();
                String name = userService.getById(entity.getUserId()).getName();
                list.add(deptName);
                idList.add(it);
                entity.setDeptName(StringUtils.join(list,","));
                entity.setUserName(name);
                entity.setDeptId(StringUtils.join(idList,","));
            });
        }
        return entity;
    }

    @Override
    public void create(Map<String, Object> map) {
        //盘点计划基本信息
        Map baseInfos = (Map) map.get("baseInfo");
        AssetsCheckPlan baseInfo = JSON.parseObject(JSON.toJSONString(baseInfos), AssetsCheckPlan.class);
        //todo
        baseInfo.setCreateTime(new Date());
        baseInfo.setCreateUser("测试人员");
        baseInfo.setCreateUserId("superuser");
        baseInfo.setReviewUser(userService.getById(baseInfo.getReviewUserId()).getName());
        baseMapper.insert(baseInfo);
        //盘点计划明细信息
        List detailsInfos = (List) map.get("detailsInfo");
        for (int a = 0; a < detailsInfos.size(); a++) {
            AssetsCheckDetailed detailsInfo = JSON.parseObject(JSON.toJSONString(detailsInfos.get(a)), AssetsCheckDetailed.class);
            Integer planType = baseInfo.getPlanType();
            if(1 == planType){
                List<String> areaIds = Arrays.asList(detailsInfo.getAreaId().split(","));
                List<String> areaNames = Arrays.asList(detailsInfo.getAreaName().split(","));
                for (int i = 0; i < areaIds.size(); i++) {
                    String areaId = areaIds.get(i);
                    String areaName = areaNames.get(i);
                    detailsInfo.setAreaId(areaId);
                    detailsInfo.setAreaName(areaName);
                    detailsInfo.setCheckUser(userService.getById(detailsInfo.getCheckUserId()).getName());
                    detailsInfo.setCheckUserId(detailsInfo.getCheckUserId());
                    detailsInfo.setPlanId(baseInfo.getPlanId());
                    detailedService.save(detailsInfo);
                }
            }else {
                List<String> deptIds = Arrays.asList(detailsInfo.getDeptId().split(","));
                List<String> deptNames = Arrays.asList(detailsInfo.getDeptName().split(","));
                for (int i = 0; i < deptIds.size(); i++) {
                    String deptId = deptIds.get(i);
                    String deptName = deptNames.get(i);
                    detailsInfo.setDeptId(deptId);
                    detailsInfo.setDeptName(deptName);
                    detailsInfo.setCheckUser(userService.getById(detailsInfo.getCheckUserId()).getName());
                    detailsInfo.setCheckUserId(detailsInfo.getCheckUserId());
                    detailsInfo.setPlanId(baseInfo.getPlanId());
                    detailedService.save(detailsInfo);
                }
            }
        }

    }

    @Override
    public void suspend(String planId) {
        baseMapper.suspend(planId);
    }
}
